#!/usr/bin/python

import Image, ImageDraw
import sys

width = 1024+1
height = 600+1                  # the actual height is one more (for header) than this value

im = Image.new("RGB", (width, height), (255,255,255))
draw = ImageDraw.Draw(im)

cur_point = [1,2]

# the header (add one more line)
def add_header(header):
    for i,v in enumerate(header):
        draw.point((i,0), fill=(v,0,0))

def next_point():
    if cur_point[0] < width-1-3:
        cur_point[0] += 4
    else:
        cur_point[0] = 1
        cur_point[1] += 4
        assert cur_point[1] <= height-1-3

def save_byte(byte):
    for row in range(3):
        for col in range(3):
            pos = (cur_point[0]+col, cur_point[1]+row)
            draw.point(pos, fill=(byte,0,0))
    next_point()


magic_code = [0x12, 0x34, 0x56, 0x14, 0x36, 0x54, 0x16, 0x34]

# header
header = magic_code + [(width>>8)&0xff, width&0xff] + [(height>>8)&0xff, height&0xff]
add_header(header)
# grid, the first line is reversed for the header
for row in range(1,height,4):
    draw.line((0,row,width-1,row),fill=(0,0,255))
for col in range(0,width,4):
    draw.line((col,1,col,height-1), fill=(0,0,255))


f = open(sys.argv[1], "rb")
dat = f.read()
data_length = len(dat)
f.close()

print "length of data:", data_length

# # magic code
# for i in magic_code:
#     save_byte(i)
# # width
# save_byte((width>>8)&0xff)
# save_byte(width&0xff)
# # height
# save_byte((height>>8)&0xff)
# save_byte(height&0xff)

# data length
for i in range(24,-8,-8):
    save_byte((data_length>>i) & 0xff)

for i in dat:
    save_byte(ord(i))

im.save("test.png")
